buildRequest = require '../bin/libs/build-request'
zip = require '../bin/libs/zip'
fsp = require '../bin/libs/fs-promises'
_ = require 'underscore'
Q = require 'q'
module.exports = (app) ->

  sandbox_path = app.get('sandbox_path')

  # 生成应用
  app.post '/api/generator', (req, res, next) ->

    res.setTimeout 1000*60*12 # express默认2min

    # tempProject 压缩后保存的位置
    app_id = req.body.app_id
    pathDir = "#{sandbox_path}#{app_id}"
    zipFile = "#{pathDir}-build.zip"
    pathDirBuild = "#{pathDir}-build"
    #文件重命名操作
    fsp.remove_safe pathDirBuild
    .then ->
      fsp.copy pathDir, pathDirBuild
      .then ->
        console.log '开始zip'
        zip(pathDirBuild, zipFile)
        .then (tempProject) ->
          console.log tempProject
          buildRequest tempProject, {
            platform: req.body.platform
            bundleIdentifier: req.body.bundleIdentifier || "com.yonyou.innovation.xxx"
            title: req.body.title || '企业空间'
            cer_pw: req.body.cer_pw
            }
        .then (obj) ->
          res.status(200).json({code: 0, data: JSON.parse obj})
    .catch (e) ->
      res.status(404).json({code: 404, data: e})
